import { deleteChat } from '@/db';
import { auth } from '@clerk/nextjs/server';
import { NextResponse } from 'next/server';

export async function POST(req: Request) {
  try {
    const { chatId } = await req.json();
    const { userId } = await auth()

    if (!userId) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      );
    }

    const deletedChat = await deleteChat(chatId, userId);

    if (!deletedChat) {
      return NextResponse.json(
        { error: '删除对话失败或对话不存在' },
        { status: 404 }
      );
    }

    return NextResponse.json(
      { success: true, deletedChat },
      { status: 200 }
    );

  } catch (error) {
    console.error('删除对话出错:', error);
    return NextResponse.json(
      { error: '服务器内部错误' },
      { status: 500 }
    );
  }
}